var amt = 0;

function processPayment(token, payerid) {

    var request = $.ajax({

        url: 'ajaxHandler.php',
        type: 'POST',
        async: true,
        data: {
            func: 'GetOrderDetails',
            token: token
        },
        beforeSend: function () {
            $(".order-details .ajx-loader").fadeIn();
            $(".status").text("Getting payment details, please wait...");
        }
    });

    request.success(function (response) {
        var msg = jQuery.parseJSON(response);

        if (msg.CHECKOUTSTATUS == 'PaymentActionNotInitiated') {
            $(".status").text("Processing payment, please wait...");
            window.amt = msg.AMT;

            $.ajax({

                url: "ajaxHandler.php",
                type: "POST",
                async: true,
                data: {
                    func: 'DoPayment',
                    token: token,
                    payerid: payerid,
                    amt: window.amt
                },
                success: function(response){

                    if(msg.ACK == 'Success'){
                        $(".status").text("Preparing order, please wait...");

                        $.ajax({

                            url: "ajaxHandler.php",
                            type: "POST",
                            async: true,
                            data: {
                                func: 'DeliverOrder'
                            },
                            success: function(response){
                                var msg = jQuery.parseJSON(response);

                                $(".status").text("Your game keys have been mailed to " + msg.email);
                                $(".order-details .ajx-loader").fadeOut();

                                updateFrontValues.updateHeaderCart(msg.items, msg.price);
                            }
                        });
                    }
                }
            });

        } else {
            $(".status").text("This order it's been already delivered");
            $(".order-details .ajx-loader").fadeOut();
        }

        console.log(msg);
    });
}

//Class to update frontend values called in ajax functions
var updateFrontValues = {

    updateHeaderCart: function (items, price) {
        $(".cart .items").empty();
        $(".cart .items").append(items);
        $(".cart .total").empty();
        $(".cart .total").append(price + ' €');
    },

    updateCheckoutCart: function (cart, price) {
        $("table").empty();
        $("table").append(cart);
        $(".checkout-total strong").empty();
        $(".checkout-total strong").append(price + " €");
    }
};